import { defineStore } from 'pinia';
import { ref,computed } from 'vue';

import type {UserInfo} from '../model/user'
import { userLogin } from '@/api/user';

export const useAccount = defineStore('userInfo', () => {
	
	// 响应式用户信息（初始值为 null）
	const userinfo = ref<UserInfo|null>(null);

	const init = (data:UserInfo)=>{
		userinfo.value = data
		uni.setStorage({
			key:'userinfo',
			data:data
		})
	}
	// 刷新用户信息
	const reset = ()=>{
		uni.getStorage({
			key:'userinfo',
			success:(res)=>{
				console.log('本地存在信息',res.data);
				userinfo.value = res.data
			},
			fail:()=>{
				console.log('本地不存在信息');
			}
		})
	}
	// 退出登录
	const logout = ()=>{
		userinfo.value = null
		uni.removeStorage({
			key:'userinfo'
		})
	}
	// 登录
	const Login = async(username:string,password:string)=>{
		try {
			let res = await userLogin(username,password)
			console.log('登录结果',res);
			if(res.statusCode === 200){
				init(res.data)
				uni.showToast({
					title:"登录成功",
					icon:'none'
				})
				uni.switchTab({
					url:'/pages/HeartIsland/index'
				})
			} 
		} catch (error) {
			console.error('登录出错:', error);
			uni.showToast({
				title: '登录请求失败，请检查网络连接',
				icon: 'none'
			});
		}
	};
	return { 
		userinfo ,
		Login,
		init,
		reset,
		logout
	}
})